package com.lp.biz.category.service.impl;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lp.biz.category.mapper.BizCategoryLabelMapper;
import com.lp.biz.category.mapper.BizCategoryMapper;
import com.lp.biz.category.model.entity.BizCategory;
import com.lp.biz.category.model.entity.BizCategoryLabel;
import com.lp.biz.category.model.vo.LabelCreate;
import com.lp.biz.category.service.LabelService;
import com.lp.common.entity.CommonAll;
import com.lp.common.exception.BaseException;
import com.lp.common.exception.ErrorCodeEnum;
import com.lp.common.utils.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.lp.common.constant.CategoryConstant.*;
import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CommonConstant.SURE;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-06-01 11:43:01
 */
@Service
public class LabelServiceImpl implements LabelService {

    @Autowired
    private BizCategoryMapper categoryMapper;

    @Autowired
    private BizCategoryLabelMapper categoryLabelMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addLabel(LabelCreate params) {
        String categoryCode = params.getCategoryCode();
        String labelName = params.getLabelName();
        if (categoryCode == null) {
            throw new BaseException("类型不能为空");
        }

        // 检查类别代码是否为支持的类型，并尝试根据类别代码获取类别信息
        if (categoryCode.equals(CODE_READING) || categoryCode.equals(CODE_STORY)
                || categoryCode.equals(CODE_FAMOUS_REMARK) || categoryCode.equals(CODE_COURSE)) {
            BizCategory category = categoryMapper.selectOne(new QueryWrapper<BizCategory>().lambda().eq(BizCategory::getCode, categoryCode));

            // 如果查询到的类别为空，则抛出参数错误异常
            if (category == null) {
                throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
            }
            BizCategoryLabel exitsLabel = categoryLabelMapper.selectOne(new QueryWrapper<BizCategoryLabel>().lambda()
                    .eq(BizCategoryLabel::getName, params.getLabelName().trim())
                    .eq(BizCategoryLabel::getBizCategoryId, category.getId())
                    .eq(BizCategoryLabel::getIsDisplay, SURE));
            if (exitsLabel != null) {
                throw new BaseException(ErrorCodeEnum.DUPLICATE_DATA);
            }
            // 创建新的标签实例并插入到数据库
            BizCategoryLabel label = new BizCategoryLabel();
            label.setName(labelName.trim());
            label.setBizCategoryId(category.getId());
            categoryLabelMapper.insert(label);
        } else {
            // 如果提供的类别代码不在支持的列表中，则抛出参数错误异常
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
    }

    @Override
    public CommonResult getLabels(String categoryCode, String name) {
        List<CommonAll> result = new ArrayList<>();
        if (categoryCode.equals(CODE_READING) || categoryCode.equals(CODE_STORY)
                || categoryCode.equals(CODE_FAMOUS_REMARK)|| categoryCode.equals(CODE_COURSE)) {
            BizCategory category = categoryMapper.selectOne(new QueryWrapper<BizCategory>().lambda().eq(BizCategory::getCode, categoryCode));
            // 如果查询到的类别为空，则抛出参数错误异常
            if (category == null) {
                throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
            }
            LambdaQueryWrapper<BizCategoryLabel> queryWrapper = new QueryWrapper<BizCategoryLabel>().lambda()
                    .eq(BizCategoryLabel::getBizCategoryId, category.getId()).eq(BizCategoryLabel::getIsDisplay, SURE)
                    .orderByAsc(BizCategoryLabel::getSort)
                    .orderByAsc(BizCategoryLabel::getCreateAt);
            if (StringUtils.isNotBlank(name)) {
                queryWrapper.like(BizCategoryLabel::getName, name);
            }
            for (BizCategoryLabel label : categoryLabelMapper.selectList(queryWrapper)) {
                result.add(new CommonAll(label.getId(), label.getName()));
            }
        }
        return CommonResult.success(result);
    }

    @Override
    public void updateLabel(Integer labelId, LabelCreate params) {
        String labelName = params.getLabelName();
        BizCategoryLabel exitsLabel = null;
        if (labelName != null) {
            exitsLabel = categoryLabelMapper.selectOne(new QueryWrapper<BizCategoryLabel>().lambda()
                    .eq(BizCategoryLabel::getName, labelName).eq(BizCategoryLabel::getIsDisplay, SURE));
        }
        BizCategoryLabel label = categoryLabelMapper.selectById(labelId);
        if (label == null || !label.getIsDisplay().equals(SURE)) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        if (exitsLabel != null && !exitsLabel.getId().equals(labelId)) {
            throw new BaseException(ErrorCodeEnum.DUPLICATE_DATA);
        } else if (exitsLabel == null) {
            label.setUpdateAt(LocalDateTime.now());
            label.setName(labelName);
            categoryLabelMapper.updateById(label);
        }
    }

    @Override
    public void deleteLabel(Integer labelId) {
        categoryLabelMapper.update(null, new UpdateWrapper<BizCategoryLabel>().lambda()
                .eq(BizCategoryLabel::getId, labelId).set(BizCategoryLabel::getIsDisplay, NEGATE)
                .set(BizCategoryLabel::getUpdateAt,  LocalDateTime.now()));
    }
}
